package com.yuwj.chinaa.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yuwj.chinaa.R;
import com.yuwj.chinaa.base.BaseActivity;
import com.yuwj.chinaa.entity.EntityBurseCoinNumber;
import com.yuwj.chinaa.presenter.IPresenter;
import com.yuwj.chinaa.presenter.presenterImpl.PresenterImpl;
import com.yuwj.chinaa.util.SharedpreferenceUtil;
import com.yuwj.chinaa.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

//转账界面
public class AssetsTransferActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_transfer_address)
    EditText etTransferAddress;
    @BindView(R.id.iv_scan)
    ImageView ivScan;
    @BindView(R.id.et_transfer_count)
    EditText etTransferAmount;
    @BindView(R.id.tv_shoux_amont)
    TextView tvServiceFee;
    @BindView(R.id.tv_real_transfer_count)
    TextView tvRealTransferAmount;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    private int REQ_CODE_WITH_DEFAULT_SCAN = 100;//请求码之二维码扫描
    IPresenter presenter;
    double serviceChargePercent;//转账服务费百分比
    double userInput;//用户转账数量
    double serviceCharge;//手续费
    double remain;//到账数量
    private AlertDialog dialogWithFailTip;
    private AlertDialog dialogWithPayPasswordInput;
    EntityBurseCoinNumber entityBurseCoinNumber;
    boolean isClickAll;


    @Override
    public int setCustomContentViewResourceId() {
        return R.layout.activity_assets_transfer;
    }

    public static Intent createIntent(Context context) {
        Intent intent = new Intent(context, AssetsTransferActivity.class);
        return intent;
    }

    @Override
    public void initParam() {
        presenter = new PresenterImpl(this);

    }

    @Override
    public void initView() {
        tvTitle.setText("转账");
        etTransferAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString().trim();
                try {
                    userInput = Double.parseDouble(s);
                    if (isClickAll){
                        serviceCharge=entityBurseCoinNumber.getAvailableBurseCoinNumber()*serviceChargePercent /100;
                    }else {
                        serviceCharge = userInput * serviceChargePercent / 100;
                    }
                    remain = userInput - serviceCharge;
                } catch (Exception e) {
                    userInput = 0;
                    serviceCharge = 0;
                    remain = 0;
                }
                tvServiceFee.setText(String.format("%.2f", serviceCharge));
                tvRealTransferAmount.setText(String.format("%.2f", userInput));
                isClickAll=false;
            }
        });

    }

    @Override
    public void initOperator() {
        JSONObject param = new JSONObject();
        presenter.getServiceChargePercent(param.toString());
        JSONObject paramWithBreseCoinNumber = new JSONObject();
        presenter.getUserBurseCoinNumberList(paramWithBreseCoinNumber.toString());
    }

    @OnClick({R.id.iv_back, R.id.iv_scan, R.id.tv_all, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.iv_scan:
                Intent intent = new Intent(context, CaptureActivity.class);
                startActivityForResult(intent, REQ_CODE_WITH_DEFAULT_SCAN);
                break;
            case R.id.tv_all:
                isClickAll=true;
                if (entityBurseCoinNumber != null) {
                    double serviceCharge=entityBurseCoinNumber.getAvailableBurseCoinNumber()*serviceChargePercent /100;
                    double allVaule=entityBurseCoinNumber.getAvailableBurseCoinNumber()-serviceCharge;
                    etTransferAmount.setText(allVaule + "");
                } else {
                    ToastUtil.getInstance().shortLength(context, "未获取到钱包数量");
                }
                break;
            case R.id.tv_confirm:
                if (TextUtils.isEmpty(etTransferAddress.getText().toString().trim())) {
                    ToastUtil.getInstance().shortLength(context, "请输入转账地址");
                    return;
                }
                if (userInput <= 0) {
                    ToastUtil.getInstance().shortLength(context, "请输入转账数量");
                    return;
                }
                if (userInput > entityBurseCoinNumber.getAvailableBurseCoinNumber()) {
                    if (dialogWithFailTip == null) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        });
                        dialogWithFailTip = builder.create();
                    }
                    dialogWithFailTip.setMessage("可用资产不足");
                    dialogWithFailTip.show();
                } else {
                    if (dialogWithPayPasswordInput == null) {
                        AlertDialog.Builder builderWithPay = new AlertDialog.Builder(context);
                        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.content_input_pay_password, null);
                        final EditText etPayPassword = (EditText) layout.findViewById(R.id.et_pay_password);
                        LinearLayout llDismiss = (LinearLayout) layout.findViewById(R.id.ll_dismiss);
                        TextView tvNextStep = (TextView) layout.findViewById(R.id.tv_buy);
                        View.OnClickListener onClickListener = new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                switch (view.getId()) {
                                    case R.id.ll_dismiss:
                                        dialogWithPayPasswordInput.dismiss();
                                        break;
                                    case R.id.tv_buy:
                                        String passwrod = etPayPassword.getText().toString();
                                        if (TextUtils.isEmpty(passwrod)) {
                                            ToastUtil.getInstance().shortLength(context, "请输入支付密码");
                                            return;
                                        }
                                        JSONObject param = new JSONObject();
                                        try {
                                            param.put("transferAccountsNum", userInput + "");
                                            param.put("transferAccountsUser", etTransferAddress.getText().toString() + "");
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        presenter.transferAccounts(param.toString());
                                        dialogWithPayPasswordInput.dismiss();
                                        break;
                                }
                            }
                        };
                        llDismiss.setOnClickListener(onClickListener);
                        tvNextStep.setOnClickListener(onClickListener);
                        dialogWithPayPasswordInput = builderWithPay.setView(layout).create();
                    }
                    dialogWithPayPasswordInput.show();
                }
                break;
        }
    }


    @Override
    public void onGetServiceChargePercentSuccess(double d) {
        super.onGetServiceChargePercentSuccess(d);
        this.serviceChargePercent = d;
    }

    @Override
    public void onGetServiceChargePercentFail(Exception e) {
        super.onGetServiceChargePercentFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
    }

    @Override
    public void onTransferAccountsSuccess() {
        super.onTransferAccountsSuccess();
        ToastUtil.getInstance().shortLength(context, "转账成功");
        finish();
    }

    @Override
    public void onTransferAccountsFail(Exception e) {
        super.onTransferAccountsFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CODE_WITH_DEFAULT_SCAN) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    etTransferAddress.setText(result + "");
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtil.getInstance().shortLength(context, "解析二维码失败");
                }
            }
        }
    }

    @Override
    public void onGetUserBurseCoinNumberListSuccess(EntityBurseCoinNumber entityBurseCoinNumber) {
        super.onGetUserBurseCoinNumberListSuccess(entityBurseCoinNumber);
        this.entityBurseCoinNumber = entityBurseCoinNumber;
    }

    @Override
    public void onGetUserBurseCoinNumberListFail(Exception e) {
        super.onGetUserBurseCoinNumberListFail(e);
        ToastUtil.getInstance().shortLength(context, "" + e.getMessage());
    }
}
